<?php

namespace App\Controller\Home;

use App\Controller\Example\CartExample;
use App\Controller\Example\CartGoodsExample;
use App\Controller\Example\UserExample;
use App\Models\CartGoodsModel;
use App\Models\CartModel;
use App\Models\Conn;
use App\Models\UsersModel;
use Core\Common\Common;
use Core\Enums\ErrorEnum;
use Core\Enums\FundsEnum;
use Core\Enums\FundsGenreEnum;
use Core\Pay\HuifuPay;
use Core\Result\Result;
use Core\Pay\AliPay;
use Core\Utils\Utils;

class Pay
{
    /**
     * 商品订单余额支付
     * entry token id
     * return json
     * */
    public function balanceBuy($data){
        $assemble = Common::assemble(new CartExample(), $data);
        $conn = new Conn();
        $userInside = UsersModel::getUserInside($conn, $assemble->token);
        $assemble->uid = $userInside["id"];
        $cartInsideId = CartModel::getCartInsideId($conn, $assemble);
        $UserExample = Common::assemble(new UserExample(), $userInside);
        if($cartInsideId["status"] != 2){
            Result::error(ErrorEnum::INVALIDORDER);
        }
        $assemble->status = $cartInsideId["status"];
        $orderType = $cartInsideId["type"];
        $orderMoney = $cartInsideId["pay_price"];
        $orderIntegral = $cartInsideId["integral"];
        if($userInside["money"] <=0 || $userInside["money"] < $orderMoney || $orderMoney<= 0){
            Result::error(ErrorEnum::INSUFFICIENTBALANCE);
        }
        $fundsData["number"] =$cartInsideId["serial"];
        $fundsData["notes"]=FundsEnum::SHOPPING;
        $fundsData["uid"] = $userInside["id"];
        $fundsData["type"]=FundsEnum::BUYGOODS;
        $conn->shiwuStart();
        $editUserMoney = UsersModel::editUserMoneyInside($conn, $orderMoney, $UserExample);
        $fundsData["genre"]=FundsGenreEnum::MONEY;
        $fundsData["amount"]=-$orderMoney;
        $fundsData["balance"]=$userInside["money"] - $orderMoney;
        $userMoneyWriteFunds = Funds::writeFunds($conn, $fundsData);
        $editPayCart = CartModel::editPayCartInside($conn, $orderMoney, $orderIntegral, "balance", $assemble);
        if($editUserMoney !=1 || $userMoneyWriteFunds !=1 || $editPayCart !=1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::PAYMENTFAILED);
        }
        if($orderType == 1){
            $CartExample = Common::assemble(new CartExample(), $cartInsideId);
            Sett::addUserAch($conn, $UserExample, $orderMoney,$CartExample);
        }
        $conn->shiwuEnd();
        Result::success("ok");
    }

    /**
     * 商品订单支付宝支付
     * entry token id
     * return json
     * */
    public function aliPayBuy($data){
        $aliPayData = self::aliPayData($data);
        Result::success(AliPay::aliPay($aliPayData));
    }
    /**
     * 商品订单支付宝支付(汇付宝)
     * entry token id
     * return json
     * */
    public function huifuAliPayBuy($data){
        $aliPayData = self::aliPayData($data);
        Result::success(HuifuPay::pay($aliPayData));
    }
    /**
     * 商品订单支付宝支付
     * entry token id
     * return json
     * */
    public function AppAliPayBuy($data){
        $aliPayData = self::aliPayData($data);
        Result::success(AliPay::aliPayApp($aliPayData));
    }
    private static function aliPayData($data){
        $assemble = Common::assemble(new CartExample(), $data);
        $conn = new Conn();
        $userInside = UsersModel::getUserInside($conn, $assemble->token);
        $assemble->uid = $userInside["id"];
        $cartInsideId = CartModel::getCartInsideId($conn, $assemble);
        if($cartInsideId["status"] != 2){
            Result::error(ErrorEnum::INVALIDORDER);
        }
        $assemble->status = $cartInsideId["status"];
        $orderMoney = $cartInsideId["pay_price"];
        $cartGoodsExample = new CartGoodsExample();
        $cartGoodsExample->uid = $assemble->uid;
        $cartGoodsExample->cid = $assemble->id;
        $payData["out_trade_no"] = $cartInsideId["serial"];
        $payData["total_amount"] = $orderMoney;
        $payData["subject"] = CartGoodsModel::getOrderCartGoodsOneNameInsideCid($conn, $cartGoodsExample);
        $payData["time_expire"] = date("Y-m-d H:i:s",time()+1800);
        $payData["NotifyUrl"] = "http://api.yiyacanyin.com/Pay/goodsAlipayCallback";
        return $payData;
    }
    /**
     * 商品订单支付宝支付(回调)
     * entry token
     * return json
     * */
    public function goodsAlipayCallback($data){
        if($data["trade_status"] == "TRADE_SUCCESS"){
            $out_trade_no = $data["out_trade_no"];
            $total_amount = $data["total_amount"];
            $trade_no = $data["trade_no"];
            $conn = new Conn();
            $serviceOrderExample = new CartExample();
            $serviceOrderExample->serial = $out_trade_no;
            $cartInsideSerial = CartModel::getCartInsideSerial($conn, $serviceOrderExample);
            if($cartInsideSerial["status"] == 2){
                $conn->shiwuStart();
                $userInside = UsersModel::getUserInsideId($conn, $cartInsideSerial["uid"]);
                $fundsData["number"] =$serviceOrderExample->serial;
                $fundsData["notes"]=FundsEnum::BUYGOODS;
                $fundsData["uid"] = $cartInsideSerial["uid"];
                $fundsData["type"]=FundsEnum::BUYGOODS;
                /*if($cartInsideSerial["integral"] > 0){
                    $fundsData["genre"]=FundsGenreEnum::TINYMONEY;
                    $fundsData["amount"]=-$cartInsideSerial["integral"];
                    $fundsData["balance"]=$userInside["tinymoney"] - $cartInsideSerial["integral"];
                    $editUserTinyMoney = UsersModel::editUserTinyMoneyInside($conn, $cartInsideSerial["integral"], Common::assemble(new UserExample(),$userInside));
                    $userTinyMoneyWriteFunds = Funds::writeFunds($conn, $fundsData);
                    if($editUserTinyMoney !=1 || $userTinyMoneyWriteFunds !=1){
                        $conn->shiwuRollback();
                        Result::error(ErrorEnum::PAYMENTFAILED);
                    }
                }*/
                $fundsData["genre"]=FundsGenreEnum::CASH;
                $fundsData["amount"]=-$total_amount;
                $fundsData["balance"]=0;
                $cartExample = new CartExample();
                $cartExample->id = $cartInsideSerial["id"];
                $cartExample->uid = $cartInsideSerial["uid"];
                $cartExample->status = $cartInsideSerial["status"];
                $userCashMoneyWriteFunds = Funds::writeFunds($conn, $fundsData);
                $editPayCart = CartModel::editPayCartInside($conn, $total_amount, $cartInsideSerial["integral"], "alipay", $cartExample);
                $UserExample = Common::assemble(new UserExample(),$userInside);

                if($userCashMoneyWriteFunds !=1 || $editPayCart !=1){
                    $conn->shiwuRollback();
                    Result::error(ErrorEnum::PAYMENTFAILED);
                }
                $CartExample = Common::assemble(new CartExample(), $cartInsideSerial);
                self::addIntegral($conn, $UserExample, $CartExample,$fundsData);
                $conn->shiwuEnd();
                Result::success("ok");
            }else{
                Utils::writePayLog("商品订单状态错误：".json_encode($data,JSON_UNESCAPED_UNICODE));
            }
        }
    }
}